<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <link rel="stylesheet" type="text/css" href="assets/css/normalize.css" />
<link rel="stylesheet" type="text/css" href="assets/css/default.css">
<link rel="stylesheet" type="text/css" href="assets/css/styles.css">
<style>
    body{
        color:white;
    }
.startDown{
    position: relative;
    top: 50%;
    font-size:.5em;
    cursor: pointer;
    z-index: 2;;
    margin:auto;
    width: 50%;
}
</style>
    <title>网络速度测试-chinlingo</title>
</head>
<body>
        <div class="zzsc-container">
<button id="startDown">开始测试</button>
<div id="msg">

</div>
<div id="print" style="padding-top:30px;"></div>
</div>
<script>
</script>
<script>
let down=(function(){
    let defaultOptions={
        process:null,
        end:null,
        start:null,
        error:null,
        url:''
    };
   function cls(options){
    let opts=Object.assign({},defaultOptions,options);
    this.loadData={
        startTime:0,
        endTime:0,
        data:{
            length:0,
            process:[]
        }
    }
    this.options=opts;
    
  }
  let log=console.log;
  cls.prototype.invoke=function(methodname,...params){
    this.options[methodname]?this.options[methodname].call(this,...params):'';
  }
  cls.prototype.start=function(url){
    var xhr=new XMLHttpRequest(),that=this,url=url?url:this.options.url;
    this.status=1;
        xhr.open('get',url);

        xhr.setRequestHeader("If-Modified-Since","0"); 
        xhr.onprogress=function(event){
            that.loadData.data.process.push([event.timeStamp-that.loadData.startTime,event.loaded]);
            that.invoke('process',event.timeStamp-that.loadData.startTime,event.loaded);
            // log(`速率：${calcspeed(event.timeStamp-that.loadData.startTime,event.loaded)}/kb`);
        }
        xhr.onreadystatechange=function(event){ 
            if(xhr.readyState==xhr.LOADING){
            }else if(xhr.readyState==xhr.HEADERS_RECEIVED){
                that.loadData.startTime=event.timeStamp;
                that.loadData.endTime=0;
                that.loadData.data.length=xhr.getResponseHeader('Content-Length');
                that.invoke('start',that.loadData.data.length);
                // msg(`开始接收数据！总共:${loadData.data.length}`);
            }else if(xhr.readyState==xhr.DONE){
                that.loadData.endTime=event.timeStamp;
                that.invoke('end',that.loadData.endTime-that.loadData.startTime,that.loadData.data.length);
                console.log(xhr,event);
                that.status=0;
                // msg(`数据接收完成!用时：${second(that.loadData.endTime-loadData.startTime).toFixed(2)},速率：${calcspeed(loadData.endTime-loadData.startTime,loadData.data.length)}/kb`);
            }
        }
        xhr.ontimeout=function(err){
            log('与服务器连接失败！');
            that.invoke('error',err);

        }
        xhr.onerror=function(err){
            log('发生了错误！',err.message);
            that.invoke('error',err);
        }
        xhr.send();
  }
  cls.prototype.calcspeed= function calcspeed(time,len){
     return (this.humanLengh(len)/this.second(time)).toFixed(2);
    }
    cls.prototype.second=  function second(time){
        return time/1000;
    }
    cls.prototype.humanLengh= function humanLengh(len,unit){
        switch(unit){
            case 'm':
                return len/1024/1024;
                break;
            default :
                return len/1024;
        }
    } 
  return cls;

})();  
let downInstance=new down({
    process:function(time,len){
        // let time=0,len=0,prod;
        // if(prod=this.loadData.data.process)
        // {
             
        // }
        document.getElementById('print').innerHTML=`当前速度${this.calcspeed(time,len)}/KB`;
    },
    start:function(len){
        document.getElementById('msg').innerHTML='';
        document.getElementById('msg').innerHTML=`总共：${this.humanLengh(len,'m').toFixed(2)}MB`
    },end:function(time,len){
        document.getElementById('msg').innerHTML=`${ document.getElementById('msg').innerHTML}</br>用时：${this.second(time).toFixed(1)}秒，平均速率：${this.calcspeed(time,len)}/KB`
    }
});
document.getElementById('startDown').addEventListener('click',function(){
    if(downInstance.status==1)
    return ;
    downInstance.start('/2');
})
// downInstance.start('/2');
</script>
</body>
</html>
